package com.xhorse.lockplatform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xhorse.lockplatform.comm.constant.ConstantDefineUtil;
import com.xhorse.lockplatform.comm.constant.ConstantString;
import com.xhorse.lockplatform.comm.model.BaseMessage;
import com.xhorse.lockplatform.comm.service.BaseService;
import com.xhorse.lockplatform.comm.util.RequestUtils;
import com.xhorse.lockplatform.dao.mapper.XhKeyMapper;
import com.xhorse.lockplatform.dao.mapper.XhProductMapper;
import com.xhorse.lockplatform.model.XhProduct;
import com.xhorse.lockplatform.model.pojo.DataBean;
import com.xhorse.lockplatform.service.CreditsExchangeService;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CreditsExchangeServiceImpl extends BaseService<XhProduct> implements CreditsExchangeService {

    @Autowired
    private XhProductMapper xhProductMapper;

    @Autowired
    private XhKeyMapper xhKeyMapper;

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 获取兑换产品列表
     */
    @Override
    public String selectProductByType(HttpServletRequest httpServletRequest) {
        String languageId = httpServletRequest.getParameter("languageId");
        String typeId = httpServletRequest.getParameter("type");
        String ip = RequestUtils.getRemoteIp(httpServletRequest);
        String customerId = httpServletRequest.getParameter("customerId");
        String verToken = httpServletRequest.getHeader("verToken");

        RequestBody requestBody = new FormBody.Builder().add("ip", ip)
                .add("languageId", languageId).add("type", typeId)
                .add("customerId", customerId).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_EXCHANGEBLELIST, requestBody, verToken);
    }

    /**
     * 根据用户id获取用户绑定的设备列表
     */
    @Override
    public List<DataBean> getProductLogByUser(HttpServletRequest request,
                                              String customerId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("customerId", customerId).add("cmd", "19").build();
        String verToken = request.getHeader("verToken");
        if (verToken == null) {
            verToken = encryptToken(ConstantString.USERNAME);
        }
        String result = sendMsg(ConstantString.PHP_URL_DATATRANSFER, requestBody, verToken);
        if (result.equals("-1") || result.equals("-2")
                || result.equals("-3") || result.equals("-4")) {
            return null;
        }
        JSONObject object = JSONObject.parseObject(result);
        List<DataBean> list = JSONObject.parseArray(object.getString("data"), DataBean.class);
        if (object.getString("status").equals("1001")) {
            for (DataBean dataBean : list) {
                List<Integer> languageList = xhKeyMapper
                        .selectLanguageIdByRegion(dataBean.getRegionId());
                dataBean.setLanguageList(languageList);
            }
        }
        return list;
    }

    /**
     * 设备绑定
     */
    @Override
    public Map<String, Object> getCredits(HttpServletRequest request,
                                          String customerId, String sn) {
        BaseMessage baseMessage = new BaseMessage();
        RequestBody requestBody = new FormBody.Builder()
                .add("customerId", customerId).add("sn", sn)
                .add("cmd", "18").build();
        String verToken = request.getHeader("verToken");
        if (verToken == null) {
            verToken = encryptToken(ConstantString.USERNAME);
        }
        String result = sendMsg(ConstantString.PHP_URL_DATATRANSFER, requestBody, verToken);
        if (result.equals("-1") || result.equals("-2")
                || result.equals("-3") || result.equals("-4")) {
            return null;
        }
        JSONObject object = JSONObject.parseObject(result);
        // 获取地区id，并查询该地区对应语言列表
        if (object.getString("status").equals("1001")) {
            DataBean dataBean = JSONObject.parseObject(object.getString("data"), DataBean.class);
            int regionId = dataBean.getRegionId();
            List<Integer> languageList = xhKeyMapper.selectLanguageIdByRegion(regionId);
            Map<String, Object> data = new HashMap<>();
            data.put("regionId", regionId);
            data.put("languageList", languageList);
            baseMessage.putStatus(ConstantDefineUtil.STATUS.get("SUCCESS"));
            baseMessage.putData(data);
        } else {
            baseMessage.puterroMsg(object.getString("errorMsg"));
            baseMessage.putStatus(object.getString("status"));
        }
        return baseMessage.baseMsg;
    }

    /**
     * 设备解绑
     */
    @Override
    public String unbindingDevice(HttpServletRequest request, String customerId, String sn) {
        RequestBody requestBody = new FormBody.Builder()
                .add("customerId", customerId).add("sn", sn)
                .add("cmd", "20").build();
        String verToken = request.getHeader("verToken");
        if (verToken == null) {
            verToken = encryptToken(ConstantString.USERNAME);
        }
        String result = sendMsg(ConstantString.PHP_URL_DATATRANSFER, requestBody, verToken);
        if (result.equals("-1") || result.equals("-2")
                || result.equals("-3") || result.equals("-4")) {
            return null;
        }
        return result;
    }

    /**
     * 获取经销商列表
     */
    @Override
    public String getDealerList(HttpServletRequest httpServletRequest) {
        String ip = RequestUtils.getRemoteIp(httpServletRequest);
        RequestBody requestBody = new FormBody.Builder().add("ip", ip).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_GETDEALER, requestBody,
                httpServletRequest.getHeader("verToken"));
    }

    /**
     * 提交订单
     */
    @Override
    public String uploadOrder(HttpServletRequest httpServletRequest,
                              String requestBody) {
        RequestBody MyrequestBody = RequestBody.create(JSON, requestBody);
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_ORDER, MyrequestBody, "asdfasfd");
    }

    /**
     * 查询兑换记录
     */
    @Override
    public String getOrderList(HttpServletRequest httpServletRequest) {
        String cusotmerId = httpServletRequest.getParameter("customerId");
        RequestBody requestBody = new FormBody.Builder().add("customerId", cusotmerId).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_GETORDERLIST, requestBody,
                httpServletRequest.getHeader("verToken"));
    }

    /**
     * 积分查询
     */
    @Override
    public String queryForCredits(HttpServletRequest request) {
        String customerId = request.getParameter("customerId");
        String verToken = request.getHeader("verToken");
        RequestBody requestBody = new FormBody.Builder().add("customerId",
                customerId).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_TOTALBONUS, requestBody, verToken);
    }

    /**
     * 获取客户产品列表（兑换功能）
     */
    @Override
    public String getFunctionProductList(HttpServletRequest httpServletRequest) {
        String customerId = httpServletRequest.getParameter("customerId");
        String verToken = httpServletRequest.getHeader("verToken");
        RequestBody requestBody = new FormBody.Builder().add("customerId",
                customerId).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_GETFUNCTIONPRODUCT_LIST, requestBody, verToken);
    }

    /**
     * 获取客户产品列表（兑换功能）
     */
    @Override
    public String getPointsProductList(HttpServletRequest httpServletRequest) {
        String customerId = httpServletRequest.getParameter("customerId");
        String type = httpServletRequest.getParameter("type");
        String verToken = httpServletRequest.getHeader("verToken");
        RequestBody requestBody = new FormBody.Builder().add("customerId",
                customerId).add("type", type).build();
        return sendMsg(ConstantString.PHP_URL_CREATE_BONUS_GETPOINTSPRODUCT_LIST, requestBody, verToken);
    }

}
